import { NavBar, InfiniteScroll } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './index.module.scss'

import Icon from '@/components/MyIcon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import { ArticleInfoType, CommResType } from '@/types/data'
import dayjs from 'dayjs'
import dompurify from 'dompurify'
import {
  commentsGetAction,
  getArticleInfoAction,
  loadCommentsGetAction,
  userFollowAction,
} from '@/store/action/article'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/types/store'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import NoComment from './components/NoComment'
import CommentInput from './components/CommentInput'

const Article = () => {
  const history = useHistory()
  const params = useParams<{ id: string }>()
  const dispatch = useDispatch()
  const scrollRef = useRef<HTMLDivElement>(null)
  const authRef = useRef<HTMLDivElement>(null)
  const [showTop, setShowTop] = useState(false)
  const [showInput, setShowInput] = useState(false)
  const openShowInput = () => {
    setShowInput(true)
  }
  const closeInput = () => {
    setShowInput(false)
  }
  const info = useSelector(
    (state: RootState) => state.articleInfo
  ) as ArticleInfoType
  const followClick = () => {
    dispatch(userFollowAction())
  }
  const comm = useSelector((state: RootState) => state.comm) as CommResType
  useEffect(() => {
    dispatch(getArticleInfoAction(params.id))
    dispatch(commentsGetAction({ source: params.id, type: 'a' }))
    const scroll = () => {
      const rect = authRef.current?.getBoundingClientRect()
      if (rect!.bottom <= 45) {
        setShowTop(true)
      } else {
        setShowTop(false)
      }
    }
    scrollRef.current?.addEventListener('scroll', scroll)
    return () => {
      scrollRef.current?.removeEventListener('scroll', scroll)
    }
  }, [])
  const hasMore = comm.end_id !== comm.last_id
  console.log('hasMore', hasMore)

  useEffect(() => {
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    })
    // 获取到内容中所有的code标签
    const codes = document.querySelectorAll('.dg-html pre code')
    codes.forEach((el) => {
      // 让code进行高亮
      hljs.highlightElement(el as HTMLElement)
    })
  }, [info])
  const loadMore = async () => {
    // console.log(1)
    await dispatch(loadCommentsGetAction(params.id))
  }
  const renderArticle = () => {
    // 文章详情
    return (
      <div className="wrapper" ref={scrollRef}>
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{info.title}</h1>

            <div className="info">
              <span> {dayjs(info.pubdate).format('YYYY-MM-DD')}</span>
              <span>{info.read_count} 阅读</span>
              <span>{info.comm_count} 评论</span>
            </div>

            <div className="author" ref={authRef}>
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span className={classNames('follow', true ? 'followed' : '')}>
                {true ? '已关注' : '关注'}
              </span>
            </div>
          </div>

          <div className="content">
            <div
              className="content-html dg-html"
              dangerouslySetInnerHTML={{
                __html: dompurify.sanitize(info.content),
              }}
            />
            <div className="date">
              发布文章时间： {dayjs(info.pubdate).format('YYYY-MM-DD')}
            </div>
          </div>
        </div>

        <div className="comment">
          <div className="comment-header">
            <span>全部评论（{comm.total_count}）</span>
            <span>{info.like_count} 点赞</span>
          </div>

          <div className="comment-list">
            {comm.results?.map((v) => {
              return <CommentItem key={v.com_id} item={v} />
            })}
            {comm.results?.length === 0 && <NoComment></NoComment>}

            <InfiniteScroll hasMore={hasMore} loadMore={loadMore} />
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {showTop && (
            <div className="nav-author">
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span
                onClick={followClick}
                className={classNames(
                  'follow',
                  info.is_followed ? 'followed' : ''
                )}
              >
                {info.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter
          isCollect={info.is_collected}
          attitude={info.attitude}
          id={info.art_id}
          showInput={openShowInput}
        />
      </div>
      <CommentInput visible={showInput} close={closeInput}></CommentInput>
    </div>
  )
}

export default Article
